<?php
defined( '_VALID_MOS' ) or die( 'access denied' );

$TempTask=$task;
switch ($task) {
  case 'field_suggestion_show':
    $suggestion=unserialize(stripslashes(mosGetParam($_REQUEST, 'suggestion','')));
    HTML_JUser::field_suggestion_show($suggestion);
    $task='empty_task';
  break;
  case 'delete_integration':
    if(count($cid)>0){
      $installer = new InstallerIntegrationPlugin();
      foreach($cid as $id){
        if(!$installer->uninstall($id)){
          mosRedirect( 'index2.php?option=com_juser&task=integration_manager&install_error='.$installer->error(), "Uninstall plugin Failed" );
        }
      }
    }
    mosRedirect( 'index2.php?option=com_juser&task=integration_manager', "Uninstall plugin Success" );
    $task='empty_task';
  break;
  case 'import_integration':
    synchronize_integration($cid[0],'import');
    $task='empty_task';
  break;
  case 'export_integration':
    synchronize_integration($cid[0],'export');
    $task='empty_task';
  break;
  case 'edit_integration':
    mosredirect('index2.php?option=com_juser&task=integration_editor&id='.$cid[0]);
    $task='empty_task';
    break;
  case 'integration_editor_apply':
  case 'integration_editor_save':
    saveIntegrationComparisons($task=='integration_editor_apply'?'apply':'save');
    $task='empty_task';
    break;
  case 'integration_editor_cancel':
    mosRedirect( 'index2.php?option=com_juser&task=integration_manager' );
    $task='empty_task';
    break;
  case 'unpublishing_integration':
    publishing_integartion(0,$cid[0]);
    $task='empty_task';
    break;
  case 'publishing_integration':
    publishing_integartion(1,$cid[0]);
    $task='empty_task';
    break;
  case 'integration_editor':
    integration_editor();
    $task='empty_task';
    break;
  case 'install_integration':
    install_integration();
    $task='empty_task';
    break;
  case 'integration_manager':
    integration_manager();
    $task='empty_task';
    break;
  case 'send_newsletter_preview':
    //print'<div align="left" style="color:#0000ff"><pre>';print_r($_POST);print'</pre></div>';
    $posted_cid = unserialize(stripslashes(mosGetParam($_REQUEST, 'newsletters')));
    newsletterPreview($posted_cid);
    exit;
    break;
  case 'send_newsletter_execute':
    //print'<div align="left" style="color:#0000ff"><pre>';print_r($_POST);print'</pre></div>';
    $posted_cid = unserialize(stripslashes(mosGetParam($_REQUEST, 'newsletters')));

     $mode = mosGetParam($_REQUEST,'htmlortext','text') == text ? 0 : 1;
     $message = mosGetParam($_REQUEST,'pretext','' ).($mode? "<br>" : "\n");
     foreach($posted_cid as $content_id)
     {
      $database->setQuery("SELECT * FROM #__content where id = ".$content_id);
      $content = $database->loadObjectList();
 
      $content[0]->fulltext = str_replace('src="',  'src="'.$GLOBALS['mosConfig_live_site'].'/',  $content[0]->fulltext);
      $content[0]->fulltext = str_replace('href="', 'href="'.$GLOBALS['mosConfig_live_site'].'/', $content[0]->fulltext);
      $content[0]->introtext = str_replace('src="',  'src="'.$GLOBALS['mosConfig_live_site'].'/',  $content[0]->introtext);
      $content[0]->introtext = str_replace('href="', 'href="'.$GLOBALS['mosConfig_live_site'].'/', $content[0]->introtext);
      
      $read_more = $mode?
                   '<a href="'.$mosConfig_live_site.'/index.php?option=com_content&task=view&id='.$content[0]->id.'">Read more</a>'
                   :'Read more here: '.$mosConfig_live_site.'/index.php?option=com_content&task=view&id='.$content[0]->id;

      $message .=  ($mode? "" : "\n").'<h1>'.$content[0]->title.'</h1>'.($mode? "" : "\n")
                  . $content[0]->introtext.($mode? "<br>" : "\n")
                  . ($content[0]-> fulltext ? $read_more.($mode? "" : "\n"):'')
                  . ($mode? "" : "\n");
     }
     $message .= ($mode? "<br>" : "\n");
     $message .= mosGetParam($_REQUEST,'posttext','' );
     $message = $mode ? $message : strip_tags($message);

    JUser::SendNewsleter($message, $mode);
    mosRedirect( 'index2.php?option=com_juser&task=newsletter' );
    break;
	case 'publishing_newsletter':
		publishNewsletter( $cid, $option, 1);
		break;
	case 'unpublishing_newsletter':
		publishNewsletter( $cid, $option, 0);
		break;
	case 'next_check_email':
		$query = "SELECT count(u.id)"
			. "\n FROM `#__users` as u"
			. "\n LEFT JOIN `#__juser_users_additional_data` as uadd ON uadd.user_id = u.id "
			. "\n WHERE uadd.email_valid IS NULL";
		$database->setQuery( $query );
		$left = $database->loadResult();
		if($left <= 0)
			mosRedirect( 'index2.php?option=com_juser&task=check_email&count_next='.mosGetParam( $_REQUEST, 'count_next' ), CE_ALLUSERSVALIDATE );
		ValidateEmail(mosGetParam( $_REQUEST, 'count_next' ));
		mosRedirect( 'index2.php?option=com_juser&task=check_email&count_next='.mosGetParam( $_REQUEST, 'count_next' ), CE_VALIDATEPROCESSFINISHED );
		$task='empty_task';
		break;
	case 'fromstart_check_email':
		fromstart_check_email();
		mosRedirect( 'index2.php?option=com_juser&task=check_email&count_next='.mosGetParam( $_REQUEST, 'count_next' ), CE_VALIDATIONBEGINFROMSTART );
		$task='empty_task';
		break;
	case 'delete_check_useremail':
		$msg=removeUsers( $cid, $option );
		mosRedirect( 'index2.php?option=com_juser&task=check_email&count_next='.mosGetParam( $_REQUEST, 'count_next' ), $msg );
		$task='empty_task';
		break;
	case 'check_email':
		CheckEmail();
		$task='empty_task';
		break;
	case 'cancelnewsletter':
		mosRedirect( 'index2.php?option=com_juser&task=newsletter' );
		$task='empty_task';
		break;
	case 'send_newsletter':
    $query = "SELECT `id`, CONCAT(`title`,' (',`type`,')') as `title`"
			. "\n FROM `#__extending_field_list`"
			. "\n where `published` = 1";
		$database->setQuery( $query );
		$extend_fields = $database->loadObjectList();
    $mode = 1;
    $message = '';
    foreach($cid as $content_id)
    {
     $database->setQuery("SELECT * FROM #__content where id = ".$content_id);
     $content = $database->loadObjectList();
     
     $content[0]->fulltext  = str_replace('src="',  'src="'.$GLOBALS['mosConfig_live_site'].'/',  $content[0]->fulltext);
     $content[0]->fulltext  = str_replace('href="', 'href="'.$GLOBALS['mosConfig_live_site'].'/', $content[0]->fulltext);
     $content[0]->introtext = str_replace('src="',  'src="'.$GLOBALS['mosConfig_live_site'].'/',  $content[0]->introtext);
     $content[0]->introtext = str_replace('href="', 'href="'.$GLOBALS['mosConfig_live_site'].'/', $content[0]->introtext);
     
     $read_more = $mode?
                  '<a href="'.$mosConfig_live_site.'/index.php?option=com_content&task=view&id='.$content[0]->id.'">Read more</a>'
                  :'Read more here: '.$mosConfig_live_site.'/index.php?option=com_content&task=view&id='.$content[0]->id;
     $message .=  ($mode? "" : "\n\n").'<h1>'.$content[0]->title.'</h1>'.($mode? "" : "\n\n")
                 . $content[0]->introtext.($mode? "<br>" : "\n")
                 . ($content[0]-> fulltext ? $read_more.($mode? "<br>" : "\n"):'')
                 . ($mode? "" : "\n\n");
     $i++;
    }

    $query = "SELECT `id`, `name`"
			  . "\n FROM `#__jcs_plans`";
		$database->setQuery( $query );
		$jcs_list = $database->loadObjectList();
    HTML_JUser::newsletter_conditions($cid,$jcs_list,$extend_fields, $message);
		$task='empty_task';
		break;
	case 'delete_newsletter':
		DeletetNewsletter($cid);
		$task='empty_task';
		break;
	case 'savenewsletter':
		/*print'<pre>';print_r($_POST);print'</pre>';
		print'<pre>';var_dump($_REQUEST);print'</pre>';exit;*/
		SaveEditNewsletter();
		$task='empty_task';
		break;
	case 'newsletter':
		ShowNewsLetter();
		$task='empty_task';
		break;
	case 'edit_newsletter':
		$query = "SELECT *"
			. "\n FROM `#__juser_newsletter`"
			. "\n WHERE `id` = '".mosGetParam( $_REQUEST, 'newsletter_id' )."'";
		$database->setQuery( $query );
		$data = $database->loadObjectList();
		$task='empty_task';
	case 'new_newsletter':
		/*$query = "SELECT `id`, CONCAT(`title`,' (',`type`,')') as `title`"
			. "\n FROM `#__extending_field_list`"
			. "\n where `published` = 1";
		$database->setQuery( $query );
		$extend_fields = $database->loadObjectList();

		$query = "SELECT `id`, `name`"
			. "\n FROM `#__jcs_plans`";
		$database->setQuery( $query );
		$jcs_list = $database->loadObjectList();

		HTML_JUser::EditNewsLetter( $extend_fields, $jcs_list, $data[0] );*/
    mosRedirect( 'index2.php?option=com_content&task=new' );
		$task='empty_task';
		break;
}
function newsletterPreview($contents){
 global $database, $mosConfig_live_site;
 $mode = mosGetParam($_REQUEST,'htmlortext','text') == text ? 0 : 1;
 $message = mosGetParam($_REQUEST,'pretext','' ).($mode? "<br>" : "\n");
 foreach($contents as $content_id)
 {
  $database->setQuery("SELECT * FROM #__content where id = ".$content_id);
  $content = $database->loadObjectList();
  $read_more = $mode?
               '<a href="'.$mosConfig_live_site.'/index.php?option=com_content&task=view&id='.$content[0]->id.'">Read more</a>'
               :'Read more here: '.$mosConfig_live_site.'/index.php?option=com_content&task=view&id='.$content[0]->id;
  
  $content[0]->fulltext  = str_replace('src="',  'src="'.$GLOBALS['mosConfig_live_site'].'/',  $content[0]->fulltext);
  $content[0]->fulltext  = str_replace('href="', 'href="'.$GLOBALS['mosConfig_live_site'].'/', $content[0]->fulltext);
  $content[0]->introtext = str_replace('src="',  'src="'.$GLOBALS['mosConfig_live_site'].'/',  $content[0]->introtext);
  $content[0]->introtext = str_replace('href="', 'href="'.$GLOBALS['mosConfig_live_site'].'/', $content[0]->introtext);             
  
  $message .=  ($mode? "" : "\n\n").'<h1>'.$content[0]->title.'</h1>'.($mode? "" : "\n\n")
              . $content[0]->introtext.($mode? "<br>" : "\n")
              . ($content[0]-> fulltext ? $read_more.($mode? "<br>" : "\n"):'')
              . ($mode? "" : "\n\n");
  $i++;
 }
 $message .= mosGetParam($_REQUEST,'posttext','' );
 print $mode ? $message : nl2br(strip_tags($message));
}

function synchronize_integration( $id = 0 , $action = 'export' )
{
  global $database;
  if($id==0){$id=mosGetParam($_REQUEST, 'id');}

  $synchronize = require_integration($id);

  $database->setQuery("SELECT `export_status` FROM `#__juser_integration` WHERE `id` = '".$id."'");
  $export_status = $database->loadResult();
  if( $export_status == 0 ){
    mosRedirect( 'index2.php?option=com_juser&task=integration_manager', INTEGRATION_MESSAGE_SYNCHRONIZESTATUSISNOTREADY);
  }
  //$synchronize = new comIntegration ( $id );
  $integration_limit_start = mosGetParam($_REQUEST, 'integration_limit_start', 0);
  switch($action){
    case'export':
      if($integration_limit_start == 0) $synchronize->clean_exterior();

      $database->setQuery("SELECT `id` FROM #__users LIMIT ".$integration_limit_start." , 999999999");
      $users = $database->loadResultArray();
      $exported_percents = round($integration_limit_start/((count($users)+ $integration_limit_start)/100));
      $in_process = round(count($users)/((count($users)+ $integration_limit_start)/100));
      ?>
      <table style="width:100%;height:95%"><tr><td valign="center">
       <div style="height:50px;border:1px solid #000000;padding:10px"><table align="center" width="100%" height="100%" cellspacing="0">
         <tr>
           <td bgcolor= "#ff0000" width="<?php print $exported_percents; ?>%">&nbsp;</td>
           <td bgcolor= "Blue"    width="<?php print $in_process;?>%">&nbsp;</td>
         </tr>
       </table></div>
       <div align="center">Exported already <?php print $integration_limit_start; ?> users (<?php print $exported_percents; ?>%). In process <?php print count($users);?> users (<?php print $in_process?>%) </div>
      </td></tr></table>
      <?php
      foreach($users as $user){
        $synchronize->synchronizeFrom($user);
        $integration_limit_start++;
        if($synchronize->timesumm >= 15){
          ?>
          <form name="integration_form" action="index2.php" method="POST">
            <input type="hidden" name="option" value="com_juser">
            <input type="hidden" name="task" value="<?php print mosGetParam($_REQUEST, 'task','');?>">
            <input type="hidden" name="integration_limit_start" value="<?php print $integration_limit_start;?>">
            <input type="hidden" name="id" value="<?php print $id;?>">
          </form>
          <script language="javascript">
            setTimeout("document.integration_form.submit();", 2000);
          </script>
          <?php
          exit;
        }
      }
      $msg=INTEGRATION_MESSAGE_EXPORTFINISHEDSUCCESS;
      break;
    case'import':
      $users = $synchronize->getExteriorUserList($integration_limit_start);
      $imported_percents = round($integration_limit_start/((count($users)+ $integration_limit_start)/100));
      $in_process = round(count($users)/((count($users)+ $integration_limit_start)/100));
      ?>
      <table style="width:100%;height:95%"><tr><td valign="center">
       <div style="height:50px;border:1px solid #000000;padding:10px"><table align="center" width="100%" height="100%" cellspacing="0">
         <tr>
           <td bgcolor= "#ff0000" width="<?php print $imported_percents; ?>%">&nbsp;</td>
           <td bgcolor= "Blue"    width="<?php print $in_process;?>%">&nbsp;</td>
         </tr>
       </table></div>
       <div align="center">Imported already <?php print $integration_limit_start; ?> users (<?php print $imported_percents ?>%). In process <?php print count($users);?> users (<?php print $in_process?>%) </div>
      </td></tr></table>
      <?php

      foreach($users as $user){
        $synchronize->synchronizeIn($user);
        $integration_limit_start++;
        if($synchronize->timesumm >= 15){
          ?>
          <form name="integration_form" action="index2.php" method="POST">
            <input type="hidden" name="option" value="com_juser">
            <input type="hidden" name="task" value="<?php print mosGetParam($_REQUEST, 'task','');?>">
            <input type="hidden" name="integration_limit_start" value="<?php print $integration_limit_start;?>">
            <input type="hidden" name="id" value="<?php print $id;?>">
          </form>
          <script language="javascript">
            setTimeout("document.integration_form.submit();", 2000);
          </script>
          <?php
          exit;
        }
      }
      $msg=INTEGRATION_MESSAGE_IMPORTFINISHEDSUCCESS;
      break;
  }
  mosRedirect( 'index2.php?option=com_juser&task=integration_manager',$msg);
}

function saveIntegrationComparisons($mode='')
{
  global $database;
  $i=1;
  $component_id = mosGetParam($_REQUEST, 'id', '');
  $synchronize = require_integration($component_id);
  $database->setQuery("delete from `#__juser_integration_comparisons` where `component_id` = ".$component_id);
  $database->query();

  //$synchronize = new comIntegration ( $component_id );

  while(mosGetParam($_REQUEST, 'ident'.$i, '') != '' ){

    $ident              = mosGetParam($_REQUEST, 'ident'.$i, '');
    $name               = mosGetParam($_REQUEST, 'name'.$i, '');
    $juser_field_id     = mosGetParam($_REQUEST, 'comparison'.$i, '');
    $static_juser_field = mosGetParam($_REQUEST, 'static_juser_field'.$i, '');
    $default_value      = mosGetParam($_REQUEST, 'default'.$i, '');
    $integrate          = mosGetParam($_REQUEST, 'integrate'.$i, '');

    /*$integrate          =mosGetParam($_REQUEST, 'integrate'.$i, '')=='integrate' ? '1' :
                          (mosGetParam($_REQUEST, 'integrate'.$i, '')=='required' ? '2':
                          ((mosGetParam($_REQUEST, 'integrate'.$i, '')=='system' ? '3': ''))) ;*/

    $database->setQuery("SELECT count(`id`) FROM #__juser_integration_comparisons WHERE `ident` = '".$ident."'  AND `component_id` = '".$component_id."'");
    $control = $database->loadResult();
    if($control <=0 ){
      $query = "INSERT INTO `#__juser_integration_comparisons`"
               ."\n (ident, name, component_id, juser_field_id, static_juser_field, default_value, integrate, m_date)"
               ."\n VALUES ('".$ident."','".$name."','".$component_id."','".$juser_field_id."','".$static_juser_field."','".$default_value."','".$integrate."',NOW())";
    }
    else{
       $query = "UPDATE `#__juser_integration_comparisons` SET"
                ."\n `name` = '".$name."',"
                ."\n `juser_field_id` = '".$juser_field_id."',"
                ."\n `static_juser_field` = '".$static_juser_field."',"
                ."\n `default_value` = '".$default_value."',"
                ."\n `integrate` = '".$integrate."',"
                ."\n `m_date` = NOW()"
                ."\n WHERE `ident` = '".$ident."' AND `component_id` = '".$component_id."'";
    }
    //print $query.'<br>';
    $database->setQuery($query);
    $database->query();
    $i++;
  }
   $query = "UPDATE `#__juser_integration` SET `export_status` = ".($synchronize->is_integrationReady('export')*1)." WHERE `id` = '".$component_id."'";
   $database->setQuery($query);
   $database->query();
   //exit;
  mosRedirect( 'index2.php?option=com_juser&task='.($mode=='apply'?'integration_editor':'integration_manager').'&id='.mosGetParam($_REQUEST,'id',''),'Saved Success');
}
function publishing_integartion( $value=0, $id )
{
  global $database;
  if( $value == 1 ){
    $database->setQuery("SELECT `export_status` FROM `#__juser_integration` WHERE `id` = ".$id);
    $export_status = $database->loadResult();
    if(!$export_status) mosRedirect( 'index2.php?option=com_juser&task=integration_manager', INTEGRATION_MESSAGE_PUBLISHNOTPOSSIBLE);
  }
      $query="UPDATE `#__juser_integration` SET `published` = ".$value." WHERE `id` = ".$id;
      $database->setQuery($query);
      $database->query();
      mosRedirect( 'index2.php?option=com_juser&task=integration_manager', $value == 1 ?  INTEGRATION_MESSAGE_PUBLISHSUCCESS : INTEGRATION_MESSAGE_UNPUBLISHSUCCESS);
}
function integration_editor()
{
  global $database, $mosConfig_absolute_path;
  $integration_id = mosGetParam($_REQUEST,'id','');
  $database->setQuery("SELECT * FROM `#__juser_integration` WHERE `id` = ".$integration_id);
  $component = $database->loadObjectList();

  $query = "SELECT * FROM `#__categories` WHERE `section` = 'com_extending_field_list'";
  $database->setQuery( $query );
  $categories= $database->loadObjectList();

  /*require_once( $mosConfig_absolute_path.'/administrator/components/com_juser/integration/'.$component[0]->component.'/'.$component[0]->component.'.php' );*/

  HTML_JUser::integration_editor( $component, $categories, $integration_id );
}
function install_integration()
{
   /*
   global $mosConfig_absolute_path,$database;
   if(!is_writable($GLOBALS['mosConfig_absolute_path'].'/administrator/components/com_juser/integration/'))
     mosRedirect( 'index2.php?option=com_juser&task=integration_manager',INTEGRATION_MESSAGE_NOTWRITEABLE);
   if($_FILES['userfile']['type'] != 'text/xml')
     mosRedirect( 'index2.php?option=com_juser&task=integration_manager',INTEGRATION_MESSAGE_WRONGEXTENTION);

   $xmlDoc = new DOMIT_Lite_Document();
   $xmlDoc->resolveErrors( true );
   $xmlDoc->loadXML( $_FILES['userfile']['tmp_name'], false, true );
   $root = &$xmlDoc->documentElement;

   if(!$root)
     mosRedirect( 'index2.php?option=com_juser&task=integration_manager',INTEGRATION_MESSAGE_CANTREADXML);
   $component = $root->getElementsByPath('component', 1);
   $database->setQuery("select count(`id`) from #__juser_integration where `component` = '".$component->getText()."'");
   $count_com = $database->loadResult();

   if($count_com > 0)
     mosRedirect( 'index2.php?option=com_juser&task=integration_manager', sprintf (INTEGRATION_MESSAGE_ALREADYINSTALLED, $xml['component'] ));

   $destination = $mosConfig_absolute_path.'/administrator/components/com_juser/integration/'.$component->getText().'.xml';
   if(!copy($_FILES['userfile']['tmp_name'],$destination))
     mosRedirect( 'index2.php?option=com_juser&task=integration_manager', INTEGRATION_MESSAGE_CANTCOPYFILE);

   $query = "insert into #__juser_integration"
            ."\n (`component`,`published`,`export_status`,`import_status`,`integration_data`)"
            ."\n VALUES ('".$component->getText()."', 0, 0, 0, NOW())";
   $database->setQuery($query);
   $database->query();
   mosRedirect( 'index2.php?option=com_juser&task=integration_manager', INTEGRATION_MESSAGE_INSTALLSUCCESS);
   */

   $installer = new InstallerIntegrationPlugin();

	// Check if file uploads are enabled
	if (!(bool)ini_get('file_uploads')) {
	  mosRedirect( 'index2.php?option=com_juser&task=integration_manager', "The installer can`t continue before file uploads are enabled. Please use the install from directory method.");
	}

	// Check that the zlib is available
	if(!extension_loaded('zlib')) {
		mosRedirect( 'index2.php?option=com_juser&task=integration_manager', "The installer can`t continue before zlib is installed");
	}

	$userfile = mosGetParam( $_FILES, 'userfile', null );

	if (!$userfile) {
	  mosRedirect( 'index2.php?option=com_juser&task=integration_manager', "No file selected");
	}

	$userfile_name = $userfile['name'];

	$msg = '';
	$resultdir = uploadFile( $userfile['tmp_name'], $userfile['name'], $msg );

	if ($resultdir !== false) {
		if (!$installer->upload( $userfile['name'] )) {
			mosRedirect( 'index2.php?option=com_juser&task=integration_manager', 'Upload Integration Plugin - Upload Failed');
		}
		$ret = $installer->install();

		cleanupInstall( $userfile['name'], $installer->unpackDir() );
		mosRedirect( 'index2.php?option=com_juser&task=integration_manager&install_error= '.($ret ? '' : $installer->error()), 'Upload Integration Plugin - '.($ret ? 'Success' : 'Failed'));
	}
	else {
		mosRedirect( 'index2.php?option=com_juser&task=integration_manager', "Upload Integration Plugin -  Upload Error" );
	}
}

function uploadFile( $filename, $userfile_name, &$msg ) {
	global $mosConfig_absolute_path;
	$baseDir = mosPathName( $mosConfig_absolute_path . '/media' );

	if (file_exists( $baseDir )) {
		if (is_writable( $baseDir )) {
			if (move_uploaded_file( $filename, $baseDir . $userfile_name )) {
				if (mosChmod( $baseDir . $userfile_name )) {
					return true;
				} else {
					$msg = 'Failed to change the permissions of the uploaded file.';
				}
			} else {
				$msg = 'Failed to move uploaded file to <code>/media</code> directory.';
			}
		} else {
			$msg = 'Upload failed as <code>/media</code> directory is not writable.';
		}
	} else {
		$msg = 'Upload failed as <code>/media</code> directory does not exist.';
	}
	return false;
}

function integration_manager()
{
  global $database;
  $database->setQuery("select * from #__juser_integration");
  $integrations = $database->loadObjectList();
  HTML_JUser::integration_manager($integrations);
}

function publishNewsletter( $cid=null, $option, $value) //Publishing selected fields
{
	global $database;
	if ( is_array( $cid ) ) {
		if (count( $cid ) < 1) {
			mosRedirect( 'index2.php?option='. $option, 'Please select a field' );
		}
		foreach( $cid as $cidA ){
			$query = "update `#__content` SET `state`= ".$value." where `id` = ".$cidA;
			$database->setQuery( $query );
			$database->query();
		}
		mosRedirect( 'index2.php?option='.$option.'&task=newsletter', ($value == 0 ? NL_MESSAGE_UNPUBLISHED_SUCCESS : NL_MESSAGE_PUBLISHED_SUCCESS));
	}
}
function fromstart_check_email()
{
	global $database;
	$query = "UPDATE `#__juser_users_additional_data` ".
							"SET `mtime`= NOW(), `email_valid` = NULL ";
	$database->setQuery( $query );
	$database->query();
}
function ValidateEmail( $count_next )
{
	global $database;

	$query = "SELECT *, u.id as uuser_id"
		. "\n FROM `#__users` as u"
		. "\n LEFT JOIN `#__juser_users_additional_data` as uadd ON uadd.user_id = u.id "
		. "\n WHERE uadd.email_valid IS NULL"
		. "\n ORDER BY u.registerDate"
		. "\n limit 0,".$count_next;
	$database->setQuery( $query );
	$users = $database->loadObjectList();
	foreach($users as $user){
		$result = SnowCheckMail($user->email);
		if($result[0]){
      $query = "UPDATE `#__juser_users_additional_data` ".
							"SET `mtime`= NOW(), `email_valid` = 1 ".
							"WHERE user_id = ".$user->uuser_id;
				$database->setQuery( $query );
				$database->query();
				if($database->getAffectedRows()<=0)
				{
					$query = "INSERT INTO #__juser_users_additional_data ( `user_id` , `email_valid`) VALUES ( '".$user->uuser_id."', '1' )";
      		$database->setQuery( $query );
      		$database->query();
				}
		}
		else{
			$query = "UPDATE `#__juser_users_additional_data` ".
							"SET `mtime`= NOW(), `email_valid` = 0 ".
							"WHERE user_id = ".$user->uuser_id;
				$database->setQuery( $query );
				$database->query();
				if($database->getAffectedRows()<=0)
				{
					$query = "INSERT INTO #__juser_users_additional_data ( `user_id` , `email_valid`) VALUES ( '".$user->uuser_id."', '0' )";
      		$database->setQuery( $query );
      		$database->query();
				}
		}
	}
}
function CheckEmail()
{
	global $database, $mainframe, $mosConfig_list_limit;
	$option = 'com_juser';
	$database->setQuery( $query );
	$NewsLeters = $database->loadObjectList();
    
	$limit 			= intval( $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit ) );
	$limitstart 	= intval( $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 ) );

	$query = "SELECT *, u.id as uuser_id"
			. "\n FROM `#__users` as u"
			. "\n LEFT JOIN `#__juser_users_additional_data` as uadd ON uadd.user_id = u.id"
			. "\n WHERE uadd.email_valid = 0"
			. "\n ORDER BY `registerDate`"
			. "\n limit ".$limitstart.', '.$limit;
	$database->setQuery( $query );
	$users = $database->loadObjectList();

	$query = "SELECT count(u.id)"
			. "\n FROM `#__users` as u"
			. "\n LEFT JOIN `#__juser_users_additional_data` as uadd ON uadd.user_id = u.id"
			. "\n WHERE uadd.email_valid = 0";
	$database->setQuery( $query );
	$total = $database->loadResult();

	$query = "SELECT count(u.id)"
			. "\n FROM `#__users` as u"
			. "\n LEFT JOIN `#__juser_users_additional_data` as uadd ON uadd.user_id = u.id"
			. "\n WHERE uadd.email_valid IS NOT NULL";
	$database->setQuery( $query );
	$validated = $database->loadResult();
	$query = "SELECT count(u.id)"
			. "\n FROM `#__users` as u"
			. "\n LEFT JOIN `#__juser_users_additional_data` as uadd ON uadd.user_id = u.id"
			. "\n WHERE uadd.email_valid IS NULL";
	$database->setQuery( $query );
	$left = $database->loadResult();

	require_once( $GLOBALS['mosConfig_absolute_path'] . '/administrator/includes/pageNavigation.php' );
	$pageNav = new mosPageNav( $total, $limitstart, $limit );
	HTML_JUser::CheckEMail($users, $pageNav, $validated, $left);
}

function DeletetNewsletter( $cid )
{
	global $database;
	foreach ($cid as $id) {
	  $query = "DELETE FROM #__content WHERE id = ".$id;
    $database->setQuery( $query );
    $database->query();
	}
	mosRedirect( 'index2.php?option=com_juser&task=newsletter', 'News letters deleteed success');
}
function ShowNewsLetter()
{
	global $database, $mainframe, $mosConfig_list_limit;
	$option = 'com_juser';
	$limit 			= intval( $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit ) );
	$limitstart 	= intval( $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 ) );
	$categories = unserialize(JEConfig::get('general.newsletters_categories'));
	if(is_array($categories) && count($categories)>0){
		$in_inner='';

		foreach($categories as $category)
		{
			$in_inner .= $pr ? ',' : '';
			$in_inner .= $category;
			$pr = true;
		}
		$query = "SELECT s.`id` as `section_id`, s.name as `section_name`, c.*, #__categories.title as cat_title, #__categories.id as cat_id"
				. "\n FROM `#__content` as `c`"
				. "\n LEFT JOIN `#__sections` as `s` ON c.sectionid=s.id"
        . "\n LEFT JOIN `#__categories` ON #__categories.id=c.catid"
				. "\n " .($in_inner ? " WHERE #__categories.id IN (".$in_inner.")" : " WHERE 0")
				. "\n ORDER BY c.`ordering`, s.`ordering`"
				. "\n limit ".$limitstart.', '.$limit;
		$database->setQuery( $query );
		$NewsLeters = $database->loadObjectList();
		$query = "SELECT count(c.id)"
				. "\n FROM `#__content` as `c`"
				. "\n LEFT JOIN `#__sections` as `s` ON c.sectionid=s.id"
        . "\n LEFT JOIN `#__categories` ON #__categories.id=c.catid"
				. "\n " .($in_inner ? " WHERE #__categories.id IN (".$in_inner.")" : " WHERE 0");
		$database->setQuery( $query );
		$total = $database->loadResult();
	}
	else{
		$NewsLeters=array();
		$total=0;
	}
	require_once( $GLOBALS['mosConfig_absolute_path'] . '/administrator/includes/pageNavigation.php' );
	$pageNav = new mosPageNav( $total, $limitstart, $limit );
	HTML_JUser::ShowNewsLetter($NewsLeters, $pageNav);
}
/*function SaveEditNewsletter()
{
	global $database;
	$posted_row = NULL;
	if (!$posted_row['subject'] = mosgetparam($_REQUEST,'subject')) {
		echo "<script> alert('Subject must be filled'); window.history.go(-1); </script>\n"; exit();
	}
	if (!$posted_row['title'] = mosgetparam($_REQUEST,'title')) {
		echo "<script> alert('Title must be filled'); window.history.go(-1); </script>\n"; exit();
	}
	if (!$posted_row['message'] = mosgetparam($_REQUEST,'letter_message')) {
		echo "<script> alert('Message must be filled'); window.history.go(-1); </script>\n"; exit();
	}

	$posted_row['conditions'] =		mosgetparam( $_REQUEST, 'condition_filed_1' )
									."\n".$_REQUEST['condition__sign_1']
									."\n".mosgetparam( $_REQUEST, 'condition__sign_param1' )
									."\n".mosgetparam( $_REQUEST, 'condition_filed_2' )
									."\n".$_REQUEST['condition__sign_2']
									."\n".mosgetparam( $_REQUEST, 'condition__sign_param2' )
									."\n".mosgetparam( $_REQUEST, 'condition_filed_3' )
									."\n".$_REQUEST['condition__sign_3']
									."\n".mosgetparam( $_REQUEST, 'condition__sign_param3' );
	$posted_row['conditions'] .= ':_|:|_separator_|:|_:';
	$pr=false;
	if( count(mosgetparam( $_REQUEST, 'condition_jcs', array(), 'array' )) > 0 )
	{
		foreach(mosgetparam( $_REQUEST, 'condition_jcs', array(), 'array' ) as $cond_jcs)
		{
			$posted_row['conditions'] .= $pr ? "\n" : "";
			$posted_row['conditions'] .= $cond_jcs;
			$pr = true;
		}
	}
	if(mosgetparam($_REQUEST,'previous_task')=='new_newsletter')
	{
		$posted_row['cdate']=date("Y-m-d");
		//$posted_row['mdate']=date("Y-m-d");
		$message = 'News letter saved success';
	}
	else
	{
		$posted_row['mdate']=date("Y-m-d");
		$message = 'News letter updated success';
	}
	$row = new mosNewsLetter( $database );
	$row->bind($posted_row);
	$t=$row->storeNewsLetter(mosGetParam( $_REQUEST, 'newsletter_id' ));
	mosRedirect( 'index2.php?option=com_juser&task=newsletter', $message );
}*/
?>